package com.og.validator;

import java.io.Serializable;
import java.util.Map;

import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Named;

import org.apache.log4j.Logger;

/**
 * @author Renaud DIANA
 *
 */
@Named
@SessionScoped
@FacesValidator("newTimeSheetValidator")
public class NewTimeSheetValidator implements Validator, Serializable {

	private static final long serialVersionUID = 1L;

	// Log4j	 
	private static final Logger	log	= Logger.getLogger(NewTimeSheetValidator.class);
		
	/**
	 * Default constructor
	 */
	public NewTimeSheetValidator() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void validate(FacesContext context, UIComponent component, Object value)
			throws ValidatorException {
					
		Map<String, String> map = context.getExternalContext().getRequestParameterMap();
		
		String app = map.get("createTimeSheetForm:timeSheetApplication_input");
		String mod = map.get("createTimeSheetForm:timeSheetModule_input");
		
		log.debug("App: " + app + " Mod: " + mod);
		
		try {
			if(app.equals("Select One") && mod.equals("Select One")) {
				FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Module and/or Application must be selected", null);
				throw new ValidatorException(message);
			}
		} catch (NullPointerException e) {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Contact admin", null);
			throw new ValidatorException(message);			
		}
	}
}
